package pay

import (
	"cashcenter/utils/logx"
	"github.com/pkg/errors"
	"github.com/smartwalle/alipay/v3"
	"github.com/spf13/viper"
)

var AlipayClient *alipay.Client
var CustomTradePagePay alipay.TradePagePay

func InitAlipay() {
	client, err := alipay.New(
		viper.GetString("alipay.appid"),
		viper.GetString("alipay.privateKey"),
		viper.GetBool("alipay.onLineMode"),
	)
	if err != nil {
		logx.LogrusObj.Fatalln(errors.Wrap(err, "[ALIPAY]"))
	}
	err = client.LoadAliPayPublicKey(viper.GetString("alipay.alipayPublicKey"))
	if err != nil {
		logx.LogrusObj.Fatalln(errors.Wrap(err, "[ALIPAY]"))
	}
	CustomTradePagePay.ReturnURL = "http://47.111.152.148:30501/ctp/cashcenter/nil/alipay/return"
	CustomTradePagePay.NotifyURL = "http://47.111.152.148:30501/ctp/cashcenter/nil/alipay/notify"
	CustomTradePagePay.ProductCode = "FAST_INSTANT_TRADE_PAY"

	AlipayClient = client
}

func GetPayPage(subject, tradeNo, amount string) (string, error) {
	p := CustomTradePagePay
	p.Subject = subject
	p.OutTradeNo = tradeNo
	p.TotalAmount = amount

	res, err := AlipayClient.TradePagePay(p)
	if err != nil {
		return "", err
	}

	return res.String(), nil
}
